package com.coin.config.resourceserver;

import org.springframework.context.annotation.*;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.*;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.*;
import org.springframework.util.FileCopyUtils;

import java.nio.charset.StandardCharsets;

/**
 * @Auther: 李 力
 * @Date: 2025/5/24
 * @Description: 资源服务器的配置
 * @version: 1.0
 */
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    /*
     * 资源的拦截和放行
     * */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .disable()
                .sessionManagement().disable()
                .authorizeRequests()
                //todo 放行url,后续补充
                .antMatchers(
                        "/gt/register",
                        "/users/register",
                        "/login",
                        "/v2/api-docs",
                        "/swagger-resources/configuration/ui",//用来获取支持的动作
                        "/swagger-resources",//用来获取api-docs的URI
                        "/swagger-resources/configuration/security",//安全选项
                        "/webjars/**",
                        "/swagger-ui.html"
                ).permitAll()
                .antMatchers("/**").authenticated()
                .and().headers().cacheControl();
    }

    /*
     * 设置公钥
     *
     * */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(jwtTokenStore());
    }

    public TokenStore jwtTokenStore() {
        JwtTokenStore jwtTokenStore = new JwtTokenStore(accessTokenConverter());
        return jwtTokenStore;
    }

    @Bean //必须放在IOC容器里面
    public JwtAccessTokenConverter accessTokenConverter() {
        //验证token
        JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
        try {
            ClassPathResource classPathResource = new ClassPathResource("coinexchange.publish.txt");
            byte[] bytes = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
            String s = new String(bytes, StandardCharsets.UTF_8);
            tokenConverter.setVerifierKey(s);
            return tokenConverter;
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return null;
    }
}
